<?php

/*****************************************************************************
 * Copyright (C) 2009 Gwathuirim
 *
 * This is free software; you can redistribute it and/or modify it under the
 * terms of the GNU General Public License as published by the Free Software
 * Foundation; either version 3 of the License, or (at your option) any later
 * version.
 *
 * This is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU Public License for more details
 *
 * To obtain a copy of the GNU General Public License, please see
 * <http://www.gnu.org.licenses/>
 *****************************************************************************/
 
require_once('class.reportmail.php');
 
class MultiReportMail extends ReportMail {

	var $reports;

	public function __construct($reports, $environmentVars) {
		parent::__construct($environmentVars);
		
		$this->reports = $reports;
	}
	
	public function send($recipient) {
		$mail = $this->setupMail($recipient);
		
		$subjectTpl = $this->createTemplate($this->environmentVars->language."/multiReportMailSubject.tpl");
		$mail->Subject = $subjectTpl->fetch();
		
		$bodyTpl = $this->createTemplate($this->environmentVars->language."/multiReportMail.tpl");
		
		//Fetch report contents
		$reportContents = array();
		for ($i = count($this->reports) - 1; $i >= 0; $i--) {
			$reportTpl = $this->createTemplate($this->environmentVars->language."/".$this->reports[$i]->type."Report.tpl");
			$reportTpl->set('report', $this->reports[$i]);
			$reportContents[] = $reportTpl->fetch();
		}
		
		//Set reportContents array
		$bodyTpl->set('reportContents', $reportContents);
		$mail->Body = $bodyTpl->fetch();
		
		$result = new stdClass();
		if ($mail->Send()) {
			for ($i = 0; $i < count($this->reports); $i++) {
				$reportId = $this->reports[$i]->id;
				
				$result->$reportId = new stdClass();
				$result->$reportId->code = CODE_MAILSENDOK;
			}
		} else {
			for ($i = 0; $i < count($this->reports); $i++) {
				$reportId = $this->reports[$i]->id;
				
				$result->$reportId = new stdClass();
				$result->$reportId->code = CODE_MAILSENDOK;
				$result->$reportId->message = $mail->ErrorInfo;
			}
		}
		
		return $result;
	}
	
	public function createTemplate($filename, $report = null) {
		$resultTpl = parent::createTemplate($filename);
		$resultTpl->set('reports', $this->reports);
		if ($report != null)
			$resultTpl->set('report', $report);
		
		return $resultTpl;
	}
}
 
?>